package com.lzq.chatroom_project.common.config.redis_caffeine_config;

import com.github.benmanes.caffeine.cache.Cache;
import com.github.benmanes.caffeine.cache.Caffeine;
import io.lettuce.core.RedisClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import java.util.concurrent.TimeUnit;

@Configuration
public class RedisClientCacheConfig {

    /**
     * 在SpringBoot启动后运行.(轮询确保Redis挂掉后再尝试连接)
     * @param cacheFrontendContext
     * @return
     */
    @Bean
    public CommandLineRunner init(@Autowired CacheFrontendContext cacheFrontendContext) {
        return new CommandLineRunner() {
            @Override
            public void run(String... args) throws Exception {
                while (true) {
                    cacheFrontendContext.check();
                    Thread.sleep(1000);
                }
            }
        };
    }

    /**
     * 配置Caffeine本地缓存
     * @return
     */
    @Bean
    public Cache<String, Object> localCache() {
        return Caffeine.newBuilder()
                .expireAfterWrite(5, TimeUnit.MINUTES)
                .initialCapacity(100)
                .maximumSize(1000)
                .build();
    }

    /**
     * 获取redis本地客户端
     * @param lettuceConnectionFactory
     * @return
     */
    @Bean
    public RedisClient redisClient(@Autowired LettuceConnectionFactory lettuceConnectionFactory) {
        return (RedisClient) lettuceConnectionFactory.getNativeClient();
    }

    /**
     * 缓存上下文
     * @param redisClient
     * @param cache
     * @return
     */
    @Bean
    public CacheFrontendContext cacheFrontendContext(@Autowired RedisClient redisClient,
                                                     @Qualifier("localCache") Cache cache,
                                                     @Qualifier("waitingSyncDataCache") Cache waitingSyncDataCache) {
        return new CacheFrontendContext(redisClient, cache, waitingSyncDataCache);
    }

    @Bean
    public TryConnectTime tryConnectTime() {
        return new TryConnectTime();
    }


    @Bean
    public Cache<String, Object> waitingSyncDataCache() {
        return Caffeine.newBuilder()
                .expireAfterWrite(120, TimeUnit.MINUTES)
                .initialCapacity(100)
                .maximumSize(3000)
                .build();
    }
}
